﻿using System;
using System.Data;
using System.Linq;
using System.Web.Security;
using System.ComponentModel.DataAnnotations;
using Model;

namespace BLL
{
    public class Sys_Users_BLL
    {
        ExtendedDBModelContainer _db = new ExtendedDBModelContainer();

        public IQueryable<Sys_Users> Get()
        {
            return _db.Sys_Users.OrderBy(a => a.UserName);
        }

        public bool check(Guid UserId, string PassWord)
        {
            return Get(UserId).Password.Equals((UserId + PassWord).GetMD5());
        }

        public Sys_Users Get(Guid? Id)
        {
            var item = new Sys_Users();
            item.LastActivityDate = DateTime.Now;
            item.IP = "127.0.0.1";

            if (Id.HasValue)
            {
                item = _db.Sys_Users.Single(a => a.Id.Equals(Id.Value));
            }
            return item;
        }

        public Sys_Users Get(string UserId)
        {
            try
            {
                return _db.Sys_Users.Single(a => a.Id.Equals(new Guid(UserId)));
            }
            catch
            {
                return null;
            }
        }

        public Sys_Users Get(string UserName, Guid EnterpriseId)
        {
            return _db.Sys_Users.SingleOrDefault(a => a.UserName.Equals(UserName) && a.EnterpriseId.Equals(EnterpriseId));
        }

        public void Save(Guid? Id, ref Sys_Users item)
        {
            ExtendedDBModelContainer _db = new ExtendedDBModelContainer();

            if (!Id.HasValue)
            {
                item.Password = (item.Id + item.Password).GetMD5();
                _db.Sys_Users.AddObject(item);
            }
            else
            {   
                string OldPassword = Get(item.Id).Password;

                if (!item.Password.Equals(OldPassword))
                {
                    item.Password = (item.Id + item.Password).GetMD5();
                }

                _db.Sys_Users.Attach(item);
                _db.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
            }

            _db.SaveChanges();
        }

        public void ChangeTheme(Guid Id, string UserId)
        {

            var item = Get(UserId);
            item.ThemeId = Id;
            _db.SaveChanges();
        }

        public void ChangePassword(Guid UserId, string PassWord)
        {
            var item = Get(UserId);
            item.Password = (UserId + PassWord).GetMD5();
            _db.SaveChanges();
        }

        public void DeleteObject(Guid Id)
        {
            var item = new Sys_Users() { Id = Id };
            _db.Sys_Users.Attach(item);
            _db.ObjectStateManager.ChangeObjectState(item, EntityState.Deleted);
            _db.SaveChanges();
        }
    }
}
